import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
import qs from 'qs'

function redirectLogin () {
  router.push({
    name: 'login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  })
}
function refreshToken () {
  return axios.create()({
    method: 'post',
    url: '/front/user/refresh_token',
    data: qs.stringify({
      refrestoken: store.state.user.refresh_token
    })
  })
}
const request = axios.create({
  // 配置选项
  // baseURL,
  // timeout
})

request.interceptors.request.use(function (config) {
  const { user = {} } = store.state
  config.headers.Authorization = user && user.access_token
  return config
}, function (error) {
  return Promise.reject(error)
})

let isRefreshing = false
let requests: any[] = []
request.interceptors.response.use(function (response) {
  // code 2xx
  return response
}, async function (error) {
  if (error.response) { // 响应状态码超出2xx
    //
    const { status } = error.response
    let msg = ''
    if (status === 400) {
      msg = '参数错误'
    } else if (status === 401) {
      msg = '未授权'
      if (!store.state.user) {
        redirectLogin()
        return Promise.reject(error)
      }
      const req = new Promise(resolve => {
        requests.push(() => {
          resolve(request(error.config))
        })
      })
      if (!isRefreshing) {
        isRefreshing = true
        return refreshToken().then(res => {
          if (!res.data.success) {
            throw new Error('刷新token失败')
          }
          store.commit('setUser', res.data.content)
          requests.forEach(cb => cb()) // 再把请求重新发出去
          requests = []
        }).catch(err => {
          store.commit('setUser', null)
          redirectLogin()
          return Promise.reject(err)
        }).finally(() => {
          isRefreshing = false
        })
      }
      return req
    } else if (status === 403) {
      msg = '没有权限'
    } else if (status === 404) {
      msg = '资源不存在'
    } else if (status >= 500) {
      msg = '服务器错误'
    }
    Message.error(msg)
  } else if (error.request) { // 请求未发出去
    Message.error('清求超时')
  } else {
    Message.error('请求失败')
  }
  return Promise.reject(error)
})

export default request
